//////////////////////////////////////////////////////////////////////////////
//
//  Created by Philip Mulcahy on 27/09/2012.
//  Copyright (c) 2012 Philip Mulcahy. All rights reserved.
//
//  This file is part of the note-recog library.
//
//  note-recog is free software: you can redistribute it and/or modify
//  it under the terms of version 3 of the GNU Lesser General Public License 
//  as published by the Free Software Foundation.
//
//  note-recog is distributed is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.
//
//  You should have received a copy of the GNU General Public License
//  along with note-recog.  If not, see <http://www.gnu.org/licenses/>.
//
//////////////////////////////////////////////////////////////////////////////

#ifndef EDGE_DETECTOR_H
#define EDGE_DETECTOR_H

#include "Detector.h"
#include "IEventListener.h"
#include "Filter.h"
#include <iostream>
#include "Log.h"
#include <fstream>

class EdgeDetector : public Detector 
{
public:
    class Event
    {
    private:
        float _time_stamp;
    public:
        float getTimeStamp() const;
        Event(float time_stamp);
        bool operator<(const Event& rhs) const;
        bool approxEqual(const Event& rhs) const;
    };
private:
    LOG_DECLARE;
    bool _detected;
    std::unique_ptr<std::ostream> _debug;
    IEventListener<Event>& _listener;
    unsigned int _frame_count; 
    const float _fall_threshold_ema_factor;
    const float _fall_last_peak_factor;
    const float _rise_threshold_ema_factor;
    bool _fallen_since_last_event;
    float _last_peak;
    float _last_level;
    float _last_rise_threshold;
    ExponentialMovingAverage<float>* const _ema_level;
public:
    explicit EdgeDetector(IEventListener<Event>&,
                          std::unique_ptr<std::ostream> debug);
    virtual ~EdgeDetector();
private:
    EdgeDetector( const EdgeDetector& ); // not implemented
    EdgeDetector& operator=( const EdgeDetector& ); // not implemented
    void init();
    void reallySubmitFrame(const Frame& frame);
public:
    void submitFrame(const Frame& frame);
    bool detected() const;
};

std::ostream& operator<<(std::ostream& os, const EdgeDetector& rhs);

std::ostream& operator<<(std::ostream& os, const EdgeDetector::Event& rhs);

#endif
